package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Author: WangPeiLin
 * @Description: 实现具体的今日佳人功能
 * @Date: Created in 19:16 2021/1/4
 * @ModifiedBy:
 */
@Service(version = "1.0.0")  //申明是一个dubbo服务
public class RecommendUserApiImpl implements RecommendUserApi {
    //注入MongoDBTemplate模板对象去操作MongoDB数据库
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询缘分值最高的
     * @param userId
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {

        //查询最高分
        Query query=Query.query(Criteria.where("toUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("score")))
                .limit(1);
        return this.mongoTemplate.findOne(query,RecommendUser.class);
    }

    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer pageNum, Integer pageSize) {
        //分页并且排序
        PageRequest pageRequest=PageRequest.of(pageNum-1,pageSize,Sort.by(Sort.Order.desc("score")));
        //查询参数
        Query query=Query.query(Criteria.where("toUserId").is(userId)).with(pageRequest);
        List<RecommendUser> recommendUserList = this.mongoTemplate.find(query, RecommendUser.class);

        return new PageInfo<>(0,pageNum,pageSize,recommendUserList);
    }

    @Override
    public double queryScore(Long userId, Long toUserId) {
        Query query = Query.query(Criteria
                .where("toUserId").is(toUserId)
                .and("userId").is(userId));
        RecommendUser recommendUser = this.mongoTemplate.findOne(query, RecommendUser.class);
        if (null == recommendUser) {
            return 0;
        }
        return recommendUser.getScore();
    }
}
